﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;

using System.Xml.Linq;
using System.IO;

using System.Drawing;


using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

/// <summary>
/// Summary description for ImageResizer
/// </summary>
/// 

namespace WebMVC.Utils
{
    public class ImageManager 
    {
        private string path;
        

        #region Encoders and Codecs
        private static ImageCodecInfo _jpegCodec;
        private static ImageCodecInfo _pngCodec;

        public ImageCodecInfo JpegCodec
        {
            get
            {
                if (_jpegCodec == null)
                {
                    _jpegCodec = GetCodecByFormatName("JPEG");
                }
                return _jpegCodec;
            }
        }

        public ImageCodecInfo PngCodec
        {
            get
            {
                if (_pngCodec == null)
                {
                    _pngCodec = GetCodecByFormatName("PNG");
                }
                return _pngCodec;
            }
        }

        private static EncoderParameters _jpegEncoderParams;

        public EncoderParameters JpegEncoderParams
        {
            get
            {
                if (_jpegEncoderParams == null)
                {
                    _jpegEncoderParams = new EncoderParameters(1);
                    EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, 90L);
                    _jpegEncoderParams.Param[0] = encoderParam;
                }
                return _jpegEncoderParams;
            }
        }

        private static ImageCodecInfo GetCodecByFormatName(string name)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo c in codecs)
            {
                if (c.FormatDescription.Equals(name))
                {
                    return c;
                }
            }
            return null;
        }
        #endregion

        public ImageManager(string path)
        {
            this.path = path;
        }

        /// <summary>
        /// Create resized image for gallery
        /// </summary>
        /// <param name="originalImage"></param>
    


        public Image CropImage(Image img, Rectangle cropArea)
        {
            if (img.Width < cropArea.X + cropArea.Width)
            {
                cropArea.Width = img.Width - cropArea.X;
            }
            if (img.Height < cropArea.Y + cropArea.Height)
            {
                cropArea.Height = img.Height - cropArea.Y;
            }
            Bitmap bmpImage = new Bitmap(img);
            Bitmap bmpCrop = bmpImage.Clone(cropArea,
            bmpImage.PixelFormat);
            return (Image)(bmpCrop);
        }


        public Image ResizeImage(Image imgToResize, Size size)
        {
           int sourceWidth = imgToResize.Width;
           int sourceHeight = imgToResize.Height;

           float nPercent = 0;
           float nPercentW = 0;
           float nPercentH = 0;

           nPercentW = ((float)size.Width / (float)sourceWidth);
           nPercentH = ((float)size.Height / (float)sourceHeight);

           if (nPercentH < nPercentW)
              nPercent = nPercentH;
           else
              nPercent = nPercentW;

           int destWidth = (int)(sourceWidth * nPercent);
           int destHeight = (int)(sourceHeight * nPercent);

           Bitmap b = new Bitmap(destWidth, destHeight);
           Graphics g = Graphics.FromImage((Image)b);
           g.InterpolationMode = InterpolationMode.HighQualityBicubic;

           g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
           g.Dispose();

           return (Image)b;
        }

        public void ResizeImageAndSave(Image imgToResize, Size size, string path)
        {
            using (var resizedImage = this.ResizeImage(imgToResize, size))
            {
                resizedImage.Save(path, JpegCodec, JpegEncoderParams);
            }
        }

        #region Old code 
        /*public void Create(string postfix, int height)
       {

           Image image = loadImage(path);
           Image thumbnailImage = image.GetThumbnailImage(GetWidthByHeight(height),
                                                        height,
                                                        null,
                                                        IntPtr.Zero);


           int indexOfPoint = path.ToLower().LastIndexOf(".");

           String name = path.Substring(0, indexOfPoint) + postfix + path.Substring(indexOfPoint);


           thumbnailImage.Save(name, codec, encoderParams);
       }*/

        /*
        public void CreateByWidth(string postfix, int width)
        {

            Image image = loadImage(path);
            Image thumbnailImage = image.GetThumbnailImage(width,
                                                         GetHeightByWidth(width),
                                                         null,
                                                         IntPtr.Zero);

            String name = path.Substring(0, path.ToLower().LastIndexOf(".jpg")) + postfix + ".jpg";
            if (File.Exists(name))
            {
                File.Delete(name);
            }
            thumbnailImage.Save(name, codec, encoderParams);

            thumbnailImage.Dispose();

        }



        public void Create(string postfix, int height, string newPath)
        {
            using (Image image = loadImage(path))
            {
                using (Image thumbnailImage = image.GetThumbnailImage(GetWidthByHeight(height),
                                                         height, null, IntPtr.Zero))
                {
                    thumbnailImage.Save(newPath, codec, encoderParams);
                }
            }


        }

        public void Create(string postfix, int width, int height)
        {
            using (Image image = loadImage(path))
            {
                using (Image thumbnailImage = image.GetThumbnailImage(width, height, null, IntPtr.Zero))
                {
                    String name = path.Substring(0, path.ToLower().LastIndexOf(".jpg")) + postfix + ".jpg";
                    thumbnailImage.Save(name, codec, encoderParams);
                }
            }
        }
        */
        #endregion

        private int GetWidthByHeight(int height, Image image)
        {
            return Convert.ToInt32(Math.Round((Convert.ToDouble(height) / image.Height) * image.Width));
        }

        private int GetHeightByWidth(int width, Image image)
        {
            return Convert.ToInt32(Math.Round((Convert.ToDouble(width) / image.Width) * image.Height));
        }


        
    }
}